using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Win32;

namespace Universe.Farm.Service
{
    class TimeStampIO
    {
        private IStateStorage _StateStorage;
        private string _idService;
        object Sync = new object();

        public TimeStampIO(IStateStorage stateStorage, string idService)
        {
            _StateStorage = stateStorage;
            _idService = idService;
        }

        public TimeStamp Value
        {
            get
            {
                lock (Sync)
                {
                    byte[] raw = _StateStorage.Read(_idService);
                    return raw == null ? TimeStamp.Zero : TimeStamp.Parse(raw);
                }
            }
            set
            {
                lock (Sync)
                {
                    _StateStorage.Write(_idService, value.Serialize());
                }
            }
        }

        public TimeStamp GetNext()
        {
            TimeStamp ret = TimeStamp.Zero;
            try
            {
                ret = this.Value;
            }
            finally
            {
                ret.Inc();
                this.Value = ret;
            }

            return ret;
        }

    }
}
